<template>
  <uNavbar
    back-text=""
    title="登录"
    :background="{ backgroundColor: 'transparent' }"
    immersive
    :isBack="false"
    back-icon-size="30rpx"></uNavbar>

  <image w-full h-full absolute z--1 src="/pages/passport/static/bg.png"></image>
  <view class="login-page flex flex-col items-center justify-center pt-480rpx box-border px-40rpx">
    <image src="/static/logo.png" w133rpx h120rpx></image>
    <view text="#A86D00" text-24rpx mt-20rpx font-400>{{ projectName }}</view>
    <view text="#000" text-36rpx mt-80rpx font-bold>欢迎进入{{ projectName }}</view>
    <view text="#7D7D7D" text-28rpx mt-60rpx>为了能给您提供优质服务，小程序名称需要获取以下的公开信息（手机号码）</view>
    <view style="position: fixed" bottom-70rpx w-full box-border flex flex-col items-start>
      <view pl-40rpx flex items-center mb-35rpx>
        <image
          :src="isAuth ? '/pages/passport/static/select.png' : '/pages/passport/static/un_select.png'"
          w30rpx
          h30rpx
          mr-10rpx
          mt-4rpx
          @click="isAuth = !isAuth"></image>
        <text text-20rpx font-400 line-height-none>
          我已阅读并确认同意
          <text text="#FCC300" @click="$navigateTo('/pages/p?code=YSCL&type=about&title=隐私策略')">
            《用户隐私政策》
          </text>
        </text>
      </view>
      <button
        v-if="!isAuth"
        class="w670rpx! h100rpx! rounded-60rpx! flex! justify-center! items-center! text-32rpx! mb-30rpx!"
        text="#000!"
        bg="#FCC300!"
        @click="getPhoneNumberBefore()">
        使用微信登录
      </button>
      <button
        v-else
        class="w670rpx! h100rpx! rounded-60rpx! flex! justify-center! items-center! text-32rpx! mb-30rpx!"
        text="#000!"
        bg="#FCC300!"
        :disabled="isLogin"
        open-type="getPhoneNumber"
        @getphonenumber="getPhoneNumber">
        使用微信登录
      </button>
      <button
        class="w670rpx! h100rpx! rounded-60rpx! flex! justify-center! items-center! text-32rpx!"
        text="#7D7D7D!"
        bg="#D9D9D9!"
        @click="backToHome">
        暂不登录
      </button>
    </view>
  </view>
</template>

<script setup lang="ts">
import configs from '@/config/config'
import { mpAutoLogin, combineLogin } from '@/api/login'
import storage from '@/utils/storage'
import type { ToastInst } from 'nutui-uniapp'
import { useStore } from '@/store'
import uNavbar from '@/components/navbar/index.vue'
const store = useStore()
const isAuth = ref(false)
const projectName = ref<string>(configs.name)
const isLogin = ref<boolean>(false)
const toastRef = ref<ToastInst>()
const authorize = ref<any>({
  code: '',
  nickName: '',
  image: ''
})
const isDev = import.meta.env.MODE === 'development'

function backToHome() {
  uni.switchTab({
    url: '/pages/index'
  })
}
function getPhoneNumberBefore() {
  if (!isAuth.value) {
    uni.showToast({
      title: '请阅读并确认同意《用户隐私政策》',
      icon: 'none',
      duration: 3500
    })
    return
  }
}

async function getPhoneNumber(e: any) {
  let iv = e.detail.iv
  let encryptedData = e.detail.encryptedData
  if (!e.detail.encryptedData) {
    uni.showToast({
      title: '请授予手机号码权限，手机号码会和会员系统用户绑定！',
      icon: 'none',
      duration: 3500
    })
    return
  }
  const { code, image, nickName } = authorize.value
  isLogin.value = true
  toastRef.value?.showToast['loading']('登录中', {
    cover: true,
    duration: 0
  })
  try {
    const res = await mpAutoLogin({
      encryptedData,
      iv,
      code,
      image,
      nickName
    })

    if (res.data.success) {
      if (!res.data.result.token) {
        combineAccount(res.data.result)
        return
      }
      storage.setAccessToken(res.data.result.token)
      // 登录成功
      uni.showToast({
        title: '登录成功!',
        icon: 'none'
      })

      getUserInfo()
    }
  } catch (e) {
    isLogin.value = false
  }
}

async function getUserInfo() {
  const user = await store.fetchUserInfo()
  if (user.data.success) {
    storage.setUserInfo(user.data.result)
    storage.removeCurrentMember()
    const chatInfo = storage.getAiChatInfo()
    if (chatInfo && chatInfo.memberId !== user.data.result.id) {
      storage.removeAiChatInfo()
    }
    uni.navigateBack({
      delta: 1
    })
  }
}

function combineAccount(user: any) {
  uni.showModal({
    title: '提示消息',
    content: '您登陆的账号有数据可以合并,是否合并?',
    confirmText: '合并',
    cancelText: '取消',
    success: function (res) {
      combineLogin({
        isCombineLogin: res.confirm,
        uuid: user.uuid,
        username: user.username,
        nickname: user.nickname,
        avatar: user.avatar,
        phone: user.phone
      })
        .then((response) => {
          if (response.data.success) {
            storage.setAccessToken(response.data.result.token)
            // 登录成功
            uni.showToast({
              title: '登录成功!',
              icon: 'none'
            })
            getUserInfo()
          }
        })
        .finally(() => {
          isLogin.value = false
        })
    }
  })
}

function fetchAuthorizeCode() {
  //获取code
  uni.login({
    success: (res) => {
      if (res.errMsg === 'login:ok') {
        authorize.value.code = res.code
      } else {
        uni.showToast({
          title: '系统异常，请联系管理员！'
        })
      }
    }
  })
}

onMounted(() => {
  fetchAuthorizeCode()
})
</script>
<style>
page {
  width: 100%;
  height: 100%;
  overflow: hidden;
  --nut-navbar-color: transparent;
}
</style>
<style scoped lang="scss">
.login-page {
  .nut-navbar--placeholder {
    background: transparent;
  }
  .clear-style {
    all: unset;
  }
}
</style>
